package com.atguigu.controller;

import com.atguigu.bean.User;
import com.atguigu.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

@RestController
public class UserController {
    @Autowired
    private UserRepository userRepository;

    @GetMapping("/users")
    public List<User> getUsers() {
        return userRepository.findAll();
    }

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Integer id) {
        Optional<User> optional = userRepository.findById(id);
        return optional.get();
    }

    @RequestMapping("/user/add")
    public User addUser(User user) {
        userRepository.save(user);
        return user;
    }

    @RequestMapping("/user/edit")
    public User editUser(User user) {
        userRepository.save(user);
        return user;
    }

    @RequestMapping("/user/delete/{id}")
    public void deleteUser(@PathVariable("id") Integer id) {
        userRepository.deleteById(id);
    }
}
